global class AT_sendIntacctCallOut
{
	public static boolean isTest = false;
	
@future(callout=true)
public static void  main(ID AccountID, String inSessionID)
{
        Account AccObj = [Select LastModifiedById, Id, CreatedById, ServerURL__c From Account where id=:AccountID limit 1];
        User AccUserObj = null;
        ID AccIDUserObj = null;
        if(AccObj!=null) AccIDUserObj = AccObj.LastModifiedById==null?AccObj.CreatedById:AccObj.LastModifiedById;
        AccUserObj = [Select ID,Intacct_Company_ID__c from User where id=:AccIDUserObj limit 1];
        /*
        https://www.intacct.com/ia/acct/sforcerouter.phtml?.action=SYNC_CUSTOMER&.account_id={!Account.Id}&.sforcekey={!API.Session_ID}&.endpoint={!API.Partner_Server_URL_70}.mega=shared&.root=Mega-SFDC
        */
        
        String strURL = 'https://www.intacct.com/ia/acct/sforcerouter.phtml?.action=SYNC_CUSTOMER&.account_id='+AccountID+'&';
        		strURL += '.sforcekey='+inSessionID+'&.endpoint='+EncodingUtil.urlEncode(AccObj.ServerURL__c, 'UTF-8');
        		strURL += '.mega=shared&.root=Mega-SFDC&.userentity='+AccUserObj.Intacct_Company_ID__c;
        		
        System.debug('>>>>>>>>>>>>>>>> strURL: '+strURL);
        
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(strURL);
        req.setTimeout(3000);
        req.setMethod('GET');
 
        String result = '';
        if(!isTest) HttpResponse res = h.send(req);
        //result = res.getBody();
}
    
public static void sendToInTacctReq(ID THItemID)
{
	Transaction_Header__c THItem = [select ID,Name, FS_Type__c, Account__c, Class_ID__c, Class_Name__c,Employee_ID__c,FS_Currency__c,
					FS_Date__c, FS_Payment_Type__c, FS_Purchaser_Address1__c, FS_Purchaser_Address2__c, FS_Purchaser_City__c,
					FS_Purchaser_Company__c, FS_Purchaser_Country__c, FS_Purchaser_Email__c, FS_Purchaser_First_Name__c, FS_Purchaser_Last_Name__c,
					FS_Purchaser_Phone__c, FS_Purchaser_Postal_Code__c, FS_Purchaser_Region__c, FS_Reference_Number__c, FS_Referrer__c, FS_Subtotal__c,
					FS_SubtotalUSD__c, FS_Tax__c, FS_Total__c, Location_ID__c, Location_Name__c, Office__c, Parent_Class_ID__c, Parent_ID__c,
					Region__c from Transaction_Header__c where ID=:THItemID limit 1];


	AT_Debug_Log__c DLog1 = sendToInTacctRequest(THItem, null);
	AT_Debug_Log__c DLog2 = null;


	if(DLog1.Status__c == 'Success' && DLog1.Transaction_Key__c!=null && THItem.FS_Type__c!='return')
	{
		DLog2 = sendToInTacctRequest(THItem, DLog1.Transaction_Key__c);
		//insert DLog2;
	}
	
	if(isTest) DLog2 = sendToInTacctRequest(THItem, 'Test-Transaction-Key');
	
	insert DLog1;
	if(DLog2!=null) insert DLog2;
}

@future(callout=true)
public static void sendToInTacctInvoice(ID THItemID, ID prevDLogID, String inTrKey)
{
	Transaction_Header__c THItem = [select ID,Name, FS_Type__c, Account__c, Class_ID__c, Class_Name__c,Employee_ID__c,FS_Currency__c,
					FS_Date__c, FS_Payment_Type__c, FS_Purchaser_Address1__c, FS_Purchaser_Address2__c, FS_Purchaser_City__c,
					FS_Purchaser_Company__c, FS_Purchaser_Country__c, FS_Purchaser_Email__c, FS_Purchaser_First_Name__c, FS_Purchaser_Last_Name__c,
					FS_Purchaser_Phone__c, FS_Purchaser_Postal_Code__c, FS_Purchaser_Region__c, FS_Reference_Number__c, FS_Referrer__c, FS_Subtotal__c,
					FS_SubtotalUSD__c, FS_Tax__c, FS_Total__c, Location_ID__c, Location_Name__c, Office__c, Parent_Class_ID__c, Parent_ID__c,
					Region__c from Transaction_Header__c where ID=:THItemID limit 1];

	AT_Debug_Log__c DLog2 = sendToInTacctRequest(THItem, inTrKey);
	AT_Debug_Log__c DLogPrev = new AT_Debug_Log__c(ID=prevDLogID, Status__c='Failure-Resend');
	if(DLog2!=null)
	{
		insert DLog2;
		DLogPrev.Log_for_Resend__c = DLog2.id;
	}
	
	update DLogPrev;
}




@future(callout=true)
public static void sendToInTacct(ID THItemID)
{
	AT_sendIntacctCallOut.sendToInTacctReq(THItemID);
}

private static AT_Debug_Log__c sendToInTacctRequest(Transaction_Header__c THItem, String inTransactionKey)
{
	String reqQuery = getRequest4sendToInTacct(THItem, inTransactionKey);
	Http h = new http();
	HttpRequest req = new HttpRequest();
	req.setEndpoint('https://www.intacct.com/ia/xml/xmlgw.phtml');
	//req.setTimeout(3000);
	req.setMethod('POST');
	req.setHeader('Content-Type', 'x-intacct-xml-request'); 
	//req.setHeader('SOAPAction', 'http://netdocuments.com/ndApi/Login');
	req.setbody(reqQuery);
	HttpResponse res;
	if(!isTest) res = h.send(req);
		
		
	AT_Debug_Log__c DLog = new AT_Debug_Log__c();
	DLog.Request_Text__c = reqQuery;
	
	String ResStr = reqQuery;
	String TType = 'Other';
	if(ResStr.contains('<transactiontype>FastSpring Sales Order</transactiontype>')){ TType = 'Sales Order';}
	if(ResStr.contains('<transactiontype>FastSpring Sales Invoice</transactiontype>')){ TType = 'Sales Invoice';}
	DLog.Transaction_Type__c = TType;
	
	if(res!=null) DLog.Response_Text__c = res.getBody();
	DLog.Transaction_Header__c = THItem.ID;
	if(inTransactionKey==null)
	{
		DLog.Status__c = 'Failure';
		DLog.Transaction_Key__c = null;
		
			
		try
		{
			TG_XmlDom dom = new TG_XmlDom(DLog.Response_Text__c);
	    	TG_XmlNode root = dom.root;
	    	TG_XmlNode operationXN = root.getElementByTagName('operation');
	    	TG_XmlNode resultXN = operationXN.getElementByTagName('result');
	    	String sTransactionKey = resultXN.getElementByTagName('key').textContent;
	    	String sTransactionStatus = resultXN.getElementByTagName('status').textContent;
	    	if(sTransactionKey!=null && sTransactionKey!='' && sTransactionStatus!=null && sTransactionStatus!='failure')
	    	{
	    		DLog.Status__c = 'Success';
				DLog.Transaction_Key__c = sTransactionKey;
	    	}
	    	//system.debug('>>>>>>>>>>>>>>>>> orderXN key:'+resultXN.getElementByTagName('key').textContent);
		}
		catch(Exception ex){ }
	}
	else
	{
		DLog.Status__c = 'Failure';
		try
		{
			TG_XmlDom dom = new TG_XmlDom(DLog.Response_Text__c);
	    	TG_XmlNode root = dom.root;
	    	TG_XmlNode operationXN = root.getElementByTagName('operation');
	    	TG_XmlNode resultXN = operationXN.getElementByTagName('result');
	    	String sTransactionStatus = resultXN.getElementByTagName('status').textContent;
	    	if(sTransactionStatus!=null && sTransactionStatus!='failure')
	    	{
	    		DLog.Status__c = 'Success';
	    	}
		}
		catch(Exception ex){ }
		//DLog.Status__c = 'Success';
	}
	
	return DLog;
	
}



private static String getRequest4sendToInTacct(Transaction_Header__c THItem, String inTransactionKey)
{
	String xml2Send = '';
	List<WebServiceSettings__c> WSSettings = WebServiceSettings__c.getall().values();
	if(THItem!=null && WSSettings!= null && WSSettings[0] != null)
	{
		
		
		xml2Send += '<?xml version="1.0" encoding="UTF-8"?>\n';
		//xml2Send += '<!DOCTYPE request SYSTEM "intacct_request.v2.1.dtd">\n';
		xml2Send += '<request>\n';
		
		 xml2Send += '<control>\n';
		 xml2Send += '	<senderid>'+AT_Utils.htmlSpecialChars(WSSettings[0].senderid__c)+'</senderid>\n';
		 xml2Send += '	<password>'+AT_Utils.htmlSpecialChars(WSSettings[0].senderpass__c)+'</password>\n';
		 xml2Send += '	<controlid>ControlIdHere</controlid>\n';
		 xml2Send += '	<uniqueid>false</uniqueid>\n';
		 xml2Send += '	<dtdversion>2.1</dtdversion>\n';
 		 xml2Send += '</control>\n';
		
		xml2Send += '<operation>\n';
		xml2Send += '	<authentication>\n';
		xml2Send += '		<login>\n';
		xml2Send += '			<userid>'+AT_Utils.htmlSpecialChars(WSSettings[0].userid__c)+'</userid>\n';
		xml2Send += '			<companyid>'+AT_Utils.htmlSpecialChars(WSSettings[0].companyid__c)+'</companyid>\n';
		xml2Send += '			<password>'+AT_Utils.htmlSpecialChars(WSSettings[0].userpass__c)+'</password>\n';
		//xml2Send += '			<uniqueid>false</uniqueid>\n';
		//xml2Send += '			<dtdversion>3.0</dtdversion>\n';
		xml2Send += '		</login>\n';
		xml2Send += '	</authentication>\n';
		xml2Send += '	<content>\n';
		xml2Send += '		<function controlid="414EB0F1-3CD4-4aa3-917F-3A15BF326F13">\n';


		Date todayDate = date.today();
		Date todayDate1 = todayDate.addDays(1);
		Date fsDate = THItem.FS_Date__c!=null?THItem.FS_Date__c.date():null;
		if(fsDate==null) fsDate = date.today();
		
		
		xml2Send += '<create_sotransaction>\n';
		if(THItem.FS_Type__c=='return') xml2Send += '<transactiontype>FastSpring Credit Memo</transactiontype>\n';
		else if(inTransactionKey!=null) xml2Send += '<transactiontype>FastSpring Sales Invoice</transactiontype>\n';
		else xml2Send += '<transactiontype>FastSpring Sales Order</transactiontype>\n';
		xml2Send += '<datecreated>\n';
		xml2Send += '	<year>'+fsDate.year()+'</year>\n';
		xml2Send += '	<month>'+fsDate.month()+'</month>\n';
		xml2Send += '	<day>'+fsDate.day()+'</day>\n';
		xml2Send += '</datecreated>\n';
		if(inTransactionKey!=null) xml2Send += '<createdfrom>'+AT_Utils.htmlSpecialChars(inTransactionKey)+'</createdfrom>\n';
		xml2Send += '<customerid>'+AT_Utils.htmlSpecialChars(WSSettings[0].customerid__c)+'</customerid>\n';
		if(inTransactionKey!=null) xml2Send += '<documentno>'+AT_Utils.htmlSpecialChars(inTransactionKey)+'</documentno>\n';
		xml2Send += '<referenceno>'+AT_Utils.htmlSpecialChars(THItem.FS_Reference_Number__c)+'</referenceno>\n';
		xml2Send += '<termname>'+AT_Utils.htmlSpecialChars(WSSettings[0].termname__c)+'</termname>\n';
		
		xml2Send += '<datedue>\n';// added from intacct
		xml2Send += '	<year>'+todayDate1.year()+'</year>\n';
		xml2Send += '	<month>'+todayDate1.month()+'</month>\n';
		xml2Send += '	<day>'+todayDate1.day()+'</day>\n';
		xml2Send += '</datedue>\n';// added from intacct
		xml2Send += '<shipto>\n';// added from intacct
		xml2Send += '	<contactname>'+AT_Utils.htmlSpecialChars(WSSettings[0].ShipTo_CName__c)+'</contactname>\n';
		xml2Send += '</shipto>\n';// added from intacct
		xml2Send += '<billto>\n';// added from intacct
		xml2Send += '	<contactname>'+AT_Utils.htmlSpecialChars(WSSettings[0].BillTo_CName__c)+'</contactname>\n';
		xml2Send += '</billto>\n';// added from intacct		
		
				
		//xml2Send += '<externalid>FOOFOO</externalid>\n';
		xml2Send += '<basecurr>USD</basecurr>\n';
		//xml2Send += '<currency>'+THItem.FS_Currency__c+'</currency>\n';
		xml2Send += '<currency>USD</currency>\n';
		xml2Send += '<exchratetype>Intacct Daily Rate</exchratetype>\n';
		xml2Send += '<sotransitems>\n';

		for(Transaction_Detail__c TDItem : [select FS_File_URL__c, FS_File_Key__c, FS_License_Key__c,FS_License_Data__c, FS_License_Name__c, FS_Product_Name__c, Product__c, Product__r.Name, 
											Transaction_Header__c, FS_SubtotalUSD__c, Product__r.EAN__c, Product__r.Family, Product__r.Cost_Method__c, Product__r.Parent_GL_Group__c,
											Product__r.Parent_GL_Group_for_Intacct__c, Product__r.Sub_Type_1__c, Product__r.Sub_Type_2__c, FS_Quantity__c
											from Transaction_Detail__c where Transaction_Header__c=:THItem.ID])
		{
			String ProductCode = TDItem.Product__c!=null?TDItem.Product__r.Name:'';
			xml2Send += '	<sotransitem>\n';
			xml2Send += '		<itemid>'+AT_Utils.htmlSpecialChars(TDItem.FS_Product_Name__c)+'</itemid>\n';
			xml2Send += '		<itemdesc>'+AT_Utils.htmlSpecialChars(TDItem.Product__r.Name!=null?TDItem.Product__r.Name:'')+'</itemdesc>\n';
			xml2Send += '		<quantity>'+TDItem.FS_Quantity__c+'</quantity>\n';
			xml2Send += '		<unit>Each</unit>\n';
			xml2Send += '		<price>'+TDItem.FS_SubtotalUSD__c+'</price>\n';
			xml2Send += '		<locationid>'+AT_Utils.htmlSpecialChars(THItem.Location_Name__c)+'</locationid>\n';
			//xml2Send += '		<locationid>Inc_USA</locationid>\n';
			if(inTransactionKey!=null) xml2Send += '<departmentid>'+AT_Utils.htmlSpecialChars(TDItem.Product__r.Parent_GL_Group__c!=null?TDItem.Product__r.Parent_GL_Group__c:'')+'</departmentid>\n';
			xml2Send += '		<memo>'+AT_Utils.htmlSpecialChars(TDItem.Product__r.EAN__c!=null?TDItem.Product__r.EAN__c:'')+'</memo>\n';
			
			
			if(TDItem.Product__c!=null)
			{
				//xml2Send += '		<itemdesc>'+(TDItem.Product__r.Name!=null?TDItem.Product__r.Name:'')+'</itemdesc>\n';
				//xml2Send += '		<memo>'+(TDItem.Product__r.EAN__c!=null?TDItem.Product__r.EAN__c:'')+'</memo>\n';

				xml2Send += '<customfields>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>product_line_id</customfieldname>\n';
				xml2Send += '		<customfieldvalue>'+AT_Utils.htmlSpecialChars(TDItem.Product__r.Family!=null?TDItem.Product__r.Family:'')+'</customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>item_type</customfieldname>\n';
				xml2Send += '		<customfieldvalue>'+AT_Utils.htmlSpecialChars(TDItem.Product__r.Cost_Method__c!=null?TDItem.Product__r.Cost_Method__c:'')+'</customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>parent_gl_group</customfieldname>\n';
				xml2Send += '		<customfieldvalue>'+AT_Utils.htmlSpecialChars(TDItem.Product__r.Parent_GL_Group_for_Intacct__c!=null?TDItem.Product__r.Parent_GL_Group_for_Intacct__c:'')+'</customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>sub_type_1</customfieldname>\n';
				xml2Send += '		<customfieldvalue>'+AT_Utils.htmlSpecialChars(TDItem.Product__r.Sub_Type_1__c!=null?TDItem.Product__r.Sub_Type_1__c:'')+'</customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>sub_type_2</customfieldname>\n';
				xml2Send += '		<customfieldvalue>'+AT_Utils.htmlSpecialChars(TDItem.Product__r.Sub_Type_2__c!=null?TDItem.Product__r.Sub_Type_2__c:'')+'</customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>recordtype</customfieldname>\n';
				xml2Send += '		<customfieldvalue>'+AT_Utils.htmlSpecialChars(WSSettings[0].recordtypeid__c)+'</customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '</customfields>\n';

				
				//xml2Send += '		<product_line_id>'+(TDItem.Product__r.Family!=null?TDItem.Product__r.Family:'')+'</product_line_id>\n';
				//xml2Send += '		<item_type>'+(TDItem.Product__r.Cost_Method__c!=null?TDItem.Product__r.Cost_Method__c:'')+'</item_type>\n';
				//xml2Send += '		<parent_gl_group>'+(TDItem.Product__r.Parent_GL_Group__c!=null?TDItem.Product__r.Parent_GL_Group__c:'')+'</parent_gl_group>\n';
				//xml2Send += '		<sub_type_1>'+(TDItem.Product__r.Sub_Type_1__c!=null?TDItem.Product__r.Sub_Type_1__c:'')+'</sub_type_1>\n';
				//xml2Send += '		<sub_type_2>'+(TDItem.Product__r.Sub_Type_2__c!=null?TDItem.Product__r.Sub_Type_2__c:'')+'</sub_type_2>\n';
				//xml2Send += '		<recordtype>012U0000000Kzcj</recordtype>\n';
			}
			else
			{


				xml2Send += '<customfields>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>product_line_id</customfieldname>\n';
				xml2Send += '		<customfieldvalue></customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>item_type</customfieldname>\n';
				xml2Send += '		<customfieldvalue></customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>parent_gl_group</customfieldname>\n';
				xml2Send += '		<customfieldvalue></customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>sub_type_1</customfieldname>\n';
				xml2Send += '		<customfieldvalue></customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>sub_type_2</customfieldname>\n';
				xml2Send += '		<customfieldvalue></customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '	<customfield>\n';
				xml2Send += '		<customfieldname>recordtype</customfieldname>\n';
				xml2Send += '		<customfieldvalue>012U0000000Kzcj</customfieldvalue>\n';
				xml2Send += '	</customfield>\n';
				xml2Send += '</customfields>\n';


				//xml2Send += '		<product_line_id></product_line_id>\n';
				//xml2Send += '		<item_type></item_type>\n';
				//xml2Send += '		<parent_gl_group></parent_gl_group>\n';
				//xml2Send += '		<sub_type_1></sub_type_1>\n';
				//xml2Send += '		<sub_type_2></sub_type_2>\n';
				//xml2Send += '		<recordtype>012U0000000Kzcj</recordtype>\n';
				
				
				
			}
			

			//xml2Send += '		<quantity>'+TDItem.FS_Quantity__c+'</quantity>\n';
			//xml2Send += '		<unit>Each</unit>\n';
			//xml2Send += '		<locationid>'+THItem.Location_ID__c+'</locationid>\n';
			//xml2Send += '		<locationid>NHI</locationid>\n';
			//xml2Send += '		<warehouseid>SFO</warehouseid>\n';
			
			
			xml2Send += '		<revrecstartdate>\n';
			xml2Send += '			<year>'+todayDate.year()+'</year>\n';
			xml2Send += '			<month>'+todayDate.month()+'</month>\n';
			xml2Send += '			<day>'+todayDate.day()+'</day>\n';
			xml2Send += '		</revrecstartdate>\n';
			

			xml2Send += '		<projectid>WEB</projectid>\n';
			//if(inTransactionKey!=null) 
			xml2Send += '<customerid>'+AT_Utils.htmlSpecialChars(WSSettings[0].customerid__c)+'</customerid>\n';
			xml2Send += '		<classid>CONS</classid>\n';
			 
			xml2Send += '	</sotransitem>\n';
		}
		
		xml2Send += '</sotransitems>\n';
		//xml2Send += '<subtotals>\n';
		//xml2Send += '	<subtotal>\n';
		//xml2Send += '		<description>subtotal</description>\n';
		//xml2Send += '		<total>'+THItem.FS_SubtotalUSD__c+'</total>\n';
		//xml2Send += '	</subtotal>\n';
		//xml2Send += '</subtotals>\n';
		xml2Send += '</create_sotransaction>\n';
		
		
		xml2Send += '</function>\n';
		xml2Send += '</content>\n';
		xml2Send += '</operation>\n';
		xml2Send += '</request>';
		
		
	}
	return xml2Send; 

}	    
    
    
}